import os
import random
import string
from datetime import datetime
from urllib.parse import urljoin

import requests
from fake_useragent import UserAgent

base_domain = "https://www.riolis.ru/"


def create_folder_if_not_exist(folder_name: str):
    """Create folder if it doesn't exist."""
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)


def generate_random_string(length: int) -> str:
    """Generate random string of given length."""
    return "".join(random.choice(string.ascii_letters) for i in range(length))


def download_image(image_link: str, filename: str = None) -> str:
    """Download image from link. Link is relative to base_domain. """
    r = requests.get(urljoin(base_domain, image_link), headers={"User-Agent": UserAgent().random})
    filename = filename or "images/" + generate_random_string(15) + ".jpg"
    with open(filename, "wb") as f:
        f.write(r.content)
    return filename


def normalize_string(string: str) -> str:
    """Remove all , and ; from string to save it to csv"""
    return string.replace(",", " ").replace(";", ".").replace(" ", " ").replace('"', "").replace("\n", " ").replace(
        "\r", " ")


def normalize_price(price: str) -> str:
    """Normalize price. Remove all non-numeric characters."""
    return "".join(filter(lambda x: x.isdigit(), price))


def current_datetime_to_filename_format() -> str:
    """Get current datetime in filename format."""
    return datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
